from duetopia.metadata.base import *

class ISO19115(Metadata):

    def extract(self,xml=None, uri=None):
        """
        >>> file = "file:samples/iso19115.xml"
        >>> md = ISO19115()
        >>> o = md.extract(uri=file)
        >>> o[0].title
        'GlobCover Land Cover'
        >>> md.extract(uri="file:share/samples/does_not_exist")
        False
        """
        if uri is not None:
            try:
                fp = urlopen(uri)
                xml = fp.read()
                fp.close()
            except:
                return False

        i = etree.fromstring(xml)
        d = Dataset()
        data = i.find('dataIdInfo')
        # abstract dataset properties - good to have a UUID if poss
        d.title = data.find('idCitation/resTitle').text
        d.abstract = data.find('idAbs').text

        d.language = None
        lang = i.find('mdLang/languageCode')
        if lang is not None:
            for l in i.find('mdLang/languageCode').items():
                if l[0] == 'value': d.language = l[1]

        d.keywords = []
        for k in data.findall('idPurp'):
            d.keywords.append(k.text)
        for k in data.findall('descKeys/keyword'):
            d.keywords.append(k.text)

# spatial extents 
        bbox = data.find('geoBox')
        if bbox is not None:
            # get extents
            extents = {} 
            # e.g. ext = [0.2,51.2,0.3,51.4]
            extents.east = bbox.find('eastBL').text
            extents.south = bbox.find('southBL').text
            extents.west = bbox.find('westBL').text
            extents.north = bbox.find('northBL').text
                # look for projection info
            self.extents = extents
            d.srs = i.find('refSysInfo/RefSystem/refSysID/identCode').text
        
        datasource = Datasource()
        dist = i.find('distInfo/distTranOps/onLineSrc')
        linkage = dist.find('linkage')
        if linkage is not None:
            datasource.uri = linkage.text
        proto = dist.find('protocol')
        if proto is not None:
            datasource.protocol = proto.text    

        # temporal extents
        temp = data.find('dataExt/tempEle/TempExtent/exTemp/TM_GeometricPrimitive/TM_Period')
        timespan = Timespan()
        timespan.dtstart = temp.find('begin').text
        timespan.dtend = temp.find('end').text

        agent = Agent()
        agent.name = data.find('idPoC/rpIndName').text
        agent.email = data.find('idPoC/rpCntInfo/cntAddress/eMailAdd').text

        phone = data.find('idPoC/rpCntInfo/cntPhone/voiceNum')
        if phone is not None:
            agent.phone = phone.text
        self.dataset = d
        self.datasource = datasource
        self.agent = agent
        self.timespan = timespan    
        return [d, datasource, agent, timespan]

    def export(self,file=file,template='metadata/iso19115.xml'):
        context = { 'dataset' : self.dataset,
                    'extents' : self.extents,
                    'datasource': self.datasource,
                    'agent':self.agent }
        c = Context(context)
        t = loader.get_template(template)
        xml = t.render(c)
        return xml

